import json

from django.shortcuts import render
from user import models,userser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
import re
import random
from django.db.models import Q
from utils.jwttool import tooljwt
from utils.tencent import TencentCloudAPI
from utils.sendmsg import send_message
from utils.myredis import redistoll
from .tasks import send
# Create your views here.
class LogView(ModelViewSet):
    queryset = models.UserModel.objects.all()
    serializer_class = userser
    lookup_field = "id"
    lookup_url_kwarg = "id"

class Loginped(APIView):
    def post(self,request):
        # api = TencentCloudAPI()
        # result = api.captcha(
        #     request.data.get("ticket"),
        #     request.data.get("randstr"),
        #     request._request.META.get("REMOTE_ADDR"),
        # )
        # print(result)

        account = request.data.get("account")
        password = request.data.get("password")
        a1 = models.UserModel.objects.filter(Q(phone=account)|Q(email=account)|Q(username=account)).first()
        if a1 is None:
            return Response({"code":400,"massage":"账号不存在"})
        elif a1.password == password:
            data={
                "id":a1.id,
                "account":account,
                "token":tooljwt.getToken(a1.id,account)
            }
            if a1.headimg:
                data["headimg"] = a1.headimg
            else:
                data["headimg"] = "/uploads/avatar/2021/default.jpg"
            return Response({"code":200,"massage":"登录成功","data":data})
        else:
            return Response({"code": 300, "massage": "密码错误"})
class SendCode(APIView):
    def post(self,request):
        phone = request.data.get("phone")
        re_phone = re.match(r"^1[3-9]\d{9}$",phone)
        code = str(random.randint(1000, 9999))
        if re_phone:
            rediscode = redistoll.getstr(phone)
            if rediscode:
                return Response({"code":400,"massage":"请勿重复发送"})
            else:
                send.delay('18119141389',code)
                redistoll.setstr(phone,code,60*5)
                return Response({"code":200,"massage":"发送成功"})
        else:
            return Response({"msg":"手机号格式不对，验证失败","code":400})
class Login(APIView):
    def post(self,request):
        account = request.data.get("account")
        code = request.data.get("code")
        rediscode = redistoll.getstr(account)
        if code != rediscode:
           return Response({'code':400,"msg":'验证码错误'})
        info = models.UserModel.objects.filter(phone=account,isshow=1).first()
        if info is None:
            newdata = models.UserModel.objects.create(phone=account)
            token = tooljwt.getToken(newdata.id,newdata.phone)
            id = newdata.id
            return Response({"code":200,"massage":"登录成功","data":{"token":token,"id":id,"account":account}})
        token = tooljwt.getToken(info.id,info.phone)
        id = info.id
        return Response({"code":200,"massage":"登录成功","data":{"token":token,"id":id,"account":account}})

class Register(APIView):
    def get(self, request):
        phone = request.query_params.get("mobile")
        info = models.UserModel.objects.filter(Q(email=phone)|Q(username=phone)|Q(phone=phone))
        if info:
            return Response({"massage":"用户已注册，请不要重复注册","code":400})
        else:
            return Response({"massage": "手机号可用", "code": 200})
    def post(self,request):
        account = request.data.get("mobile")
        password = request.data.get('password')
        code = request.data.get('sms_code')
        rediscode = redistoll.getstr(account)
        data = {}
        if re.match(r"^1[3-9]\d{9}$",account) and code != rediscode:
          return Response({"massage":"验证码错误，注册失败","code":400})
        elif re.match(r"^1[3-9]\d{9}$",account) and code == rediscode:
            data["phone"] = account
        elif re.match(r"^[0-9a-zA-Z_]{6,14}@(qq|163|139|sina)\.com$",account):
            data["email"] = account
        else:
            data["username"] = account
        data["password"] = password
        ser = userser.UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"massage":"注册成功","code":200,"data":ser.data})
        return Response({"massage": "注册失败", "code": 400})

from .tasks import add
class TestUser(APIView):
    def post(self,requset):
        sum_ = add.delay(1,2)
        print(sum_.get())
        return Response({"code":200,"massage":"测试成功"})

from utils.authorization import MyAuthorization
class Cart(APIView):
    authentication_classes = [MyAuthorization]
    def get(self,requset):
        return Response({"code":200,"massage":"测试成功"})




